var RichEditor = function () {
  importFiles([
    "/vueSystem/components/css/vueEditor.css"
  ]);

  var defaultPlugins = ['autolink'];

  var pluginsObj = {
    autoresize: ['autoresize'], //自适应内容高度
    contextmenu: ['contextmenu'], //鼠标右键点击出现的菜单
    charmap: ['charmap'], //插入特殊符号
    emoticons: ['emoticons'], //插入表情
    hr: ['hr'], //插入水平分割线
    searchreplace: ['searchreplace'], //查找替换
    advlist: ['advlist'], //项目符号和编号列表可以有多种选择
    anchor: ['anchor'], //插入锚点
    autosave: ['restoredraft'], //恢复上一次草稿
    code: ['code'], //显示html字符串
    colorpicker: ['forecolor', 'backcolor'], //自定义颜色选择器
    directionality: ['ltr', 'rtl'], //文本方向
    fullscreen: ['fullscreen'], //全屏
    help: ['help'], //帮助文档
    image: ['image'], //插入/编辑图片
    imagetools: ['image'], //图片上传工具
  };

  var template = /* html */ `
    <div class="rich-editor" :class="{'rich-editor-fillHeight':fillHeight,'rich-editor-hasappend':hasAppendSlot}">
      <template v-if="disabled">
        <div class="vue-rich-editor" v-html="content"></div>
      </template>
      <template v-else-if="editorInit!==null">
        <vue-editor class="rich-editor-form" ref="richEditorForm" v-model="content" :init="editorInit" model-events="change keyup undo redo"
          @input="handleInput" :toolbar="toolbar" :plugins="plugins" :disabled="readonly" :initial-value="initialValue"></vue-editor>
      </template>
      <div v-if="hasAppendSlot" style="margin-top:10px;text-align:center;">
        <slot name="append" :imgFiles="imgFileList" :editor="editor"></slot>
      </div>
    </div>
  `;

  return {
    props: {
      value: {
        type: String,
        default: true
      },

      inline: {
        type: Boolean,
        default: false
      },

      height: {
        type: [Number, String],
        default: '100%'
      },

      fillHeight: {
        type: Boolean,
        default: true
      },

      plugins: {
        type: [String, Array],
        default: function () {
          return [
            'charmap',
            'advlist',
            'searchreplace',
            'colorpicker',
            'contextmenu',
            'imagetools',
            'image',
            'powerpaste template pagebreak nonbreaking insertdatetime lists textcolor wordcount spellchecker textpattern'
          ]
        }
      },

      toolbar: {
        type: [String, Array],
        default: function () {
          return [
            'undo redo | fontselect fontsizeselect | bold italic strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify',
            'charmap | numlist bullist outdent indent | searchreplace |removeformat'
          ];
        }
      },

      readonly: {
        type: Boolean,
        defualt: false
      },

      disabled: {
        type: Boolean,
        defualt: false
      },

      contextmenu: {
        type: String,
        default: 'undo redo | cut copy paste | selectall'
      }
    },

    watch: {
      value: function () {
        var useInput = this.useInput;
        if (useInput !== null) {
          this.useInput = null;
          return;
        }
        this.content = this.value;
      }
    },

    data: function () {
      return {
        content: this.value,
        useInput: null,
        editor: null,
        editorInit: null,
        readonly: false,
        basePath: SysUtil.getBasePath(),
        initialValue: '<div></div>',
        imgFileList: [],
        hasAppendSlot: false
      };
    },

    created: function () {
      this.initEditor();
    },

    mounted: function () {
      this.hasAppendSlot = this.$slots.append ||
        this.$scopedSlots.append;
    },

    methods: {
      initEditor: function () {
        var self = this;
        var sizes = [];
        for (var i = 12; i <= 50; i++) {
          sizes.push(i + 'px');
        }
        this.editorInit = {
          language: 'zh_CN',
          height: this.height,
          theme: 'modern',
          resize: false,
          contextmenu: this.contextmenu,
          branding: false,
          elementpath: false,
          inline: this.inline,
          fontsize_formats: sizes.join(" "),
          font_formats: "宋体=宋体;黑体=黑体;仿宋=仿宋;楷体=楷体;隶书=隶书;幼圆=幼圆;Arial=arial,helvetica,sans-serif;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats",
          statusbar: false,
          body_class: 'vue-rich-editor',
          content_css: `${this.basePath}/vueSystem/components/css/vueEditor.css`,
          indentation: '20px',
          automatic_uploads: true,
          image_advtab: true,
          image_title: true,
          images_upload_base_path: this.basePath,
          formats: {
            bold: {
              inline: 'span',
              styles: {
                fontWeight: 'bold'
              }
            },
            italic: {
              inline: 'span',
              styles: {
                fontStyle: 'italic'
              }
            },
          },
          menu: {
            edit: {
              title: 'Edit',
              items: 'undo redo | cut copy paste | selectall'
            },
            format: {
              title: 'Format',
              items: 'bold italic underline strikethrough | removeformat'
            }
          },
          init_instance_callback: function (editor) {
            self.editor = editor;
            self.$emit('ready', editor);

            self.$nextTick(function () {
              var $editor = $(self.$el).find('.mce-tinymce>.mce-container-body.mce-stack-layout');
              var $toolbar = $editor.find('>.mce-stack-layout-item.mce-top-part');
              var $area = $editor.find('.mce-edit-area');
              var height = $toolbar.height();
              if (height !== null) {
                $area.height(`calc(100% - ${height}px)`);
              }
            });
          },
          images_upload_handler: function (blobInfo, success, failure) {
            self.imgFileList.push({
              id: blobInfo.id(),
              file: {
                id: blobInfo.id(),
                blob: blobInfo.blob(),
                name: blobInfo.name()
              },
              blobInfo: blobInfo,
              success: success,
              failure: failure
            });
          }
        };
      },

      handleInput: function () {
        var content = this.content;
        this.useInput = content;
        this.$emit('input', content);
        this.$emit('change', content);
      },

      calContent: function () {
        var content = this.content;
        var imgFileList = this.imgFileList;
        if (imgFileList.length === 0 || content.trim() === '') {
          return Promise.resolve(content);
        }

        var $content = $(content);
        var $imgs = $content.find('img');
        if ($imgs.length === 0) {
          return Promise.resolve(content);
        }

        var uploadFiles = [];
        $imgs.each(function () {
          var src = $(this).attr('src');
          var srcType = null;
          if (src.indexOf('data:') === 0) {
            srcType = 'base64';
            src = src.split(',')[1];
          } else if (src.indexOf('blob:') === 0) {
            srcType = 'blob';
          }
          if (srcType === null) {
            return;
          }

          var imgFile = _.find(imgFileList, function (file) {
            var fileSrc;
            if (srcType === 'base64') {
              fileSrc = file.blobInfo.base64();
            } else {
              fileSrc = file.blobInfo.blobUri();
            }
            return fileSrc === src;
          });
          if (imgFile === undefined) {
            return;
          }
          imgFile.src = $(this).attr('src');
          uploadFiles.push(imgFile);
          _.remove(imgFileList, imgFile);
        });

        if (uploadFiles.length === 0) {
          return Promise.resolve(content);
        }

        var imgFileObj = {};
        var fileBlobs = _.map(uploadFiles, function (file) {
          imgFileObj[file.id] = file;
          return file.file;
        });

        var self = this;
        return postImgsToQiniu('fileManager/getQiniuToken', fileBlobs).then(function (fileUrlList) {
          for (var i = 0; i < fileUrlList.length; i++) {
            var fileUrl = fileUrlList[i];
            var id = fileUrl.id;
            var imgFile = imgFileObj[id];
            if (imgFile === undefined) {
              continue;
            }

            var url = fileUrl.url;
            if (url === undefined) {
              imgFile.failure('图片上传失败');
            } else {
              imgFile.success(url + '?imageMogr/auto-orient');
            }
          }
          self.imgFileList = [];
          var content = self.editor.getContent();
          for (var i = 0; i < fileUrlList.length; i++) {
            var fileUrl = fileUrlList[i];
            var imgFile = imgFileObj[fileUrl.id];
            if (imgFile === undefined) {
              continue;
            }

            var url = fileUrl.url;
            if (url !== undefined) {
              content = content.replace(imgFile.src,url);
            }
          }
          self.content = content;
          self.handleInput();
          return content;
        });
      }
    },

    components: {
      VueEditor: Editor
    },

    template: template
  };
}();
